package com.neusoft.lohas.modules.shop.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.neusoft.lohas.common.persistence.Page;
import com.neusoft.lohas.common.persistence.StatusBean;
import com.neusoft.lohas.common.utils.DateUtils;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.IdGen;
import com.neusoft.lohas.common.web.BaseShopController;
import com.neusoft.lohas.modules.ivm.entity.business.Activity;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityProduct;
import com.neusoft.lohas.modules.ivm.entity.business.ActivityTime;
import com.neusoft.lohas.modules.ivm.entity.business.Concession;
import com.neusoft.lohas.modules.ivm.entity.business.HangStore;
import com.neusoft.lohas.modules.ivm.entity.business.RollScreen;
import com.neusoft.lohas.modules.ivm.entity.merchant.Merchant;
import com.neusoft.lohas.modules.ivm.entity.order.ShoppingCart;
import com.neusoft.lohas.modules.ivm.entity.product.Product;
import com.neusoft.lohas.modules.ivm.entity.product.ProductClassify;
import com.neusoft.lohas.modules.ivm.service.business.ActivityProductService;
import com.neusoft.lohas.modules.ivm.service.business.ActivityService;
import com.neusoft.lohas.modules.ivm.service.business.ActivityTimeService;
import com.neusoft.lohas.modules.ivm.service.business.ConcessionService;
import com.neusoft.lohas.modules.ivm.service.business.HangStoreService;
import com.neusoft.lohas.modules.ivm.service.business.RollScreenService;
import com.neusoft.lohas.modules.ivm.service.order.ShoppingCartService;
import com.neusoft.lohas.modules.ivm.utils.ProductUtils;
import com.neusoft.lohas.modules.shop.service.BusinessService;
import com.neusoft.lohas.modules.shop.service.ShopService;
import com.neusoft.lohas.modules.shop.utils.ShopUtils;
import com.neusoft.lohas.modules.sys.entity.User;
import com.neusoft.lohas.modules.sys.utils.UserUtils;
/**
 * 乐活商圈controller类
 * @author jackie.liu
 * @version 2015-02-02
 */
@Controller
@RequestMapping(value = "${frontPath}/shops/business")
public class BusinessController extends BaseShopController {
	@Autowired
	private BusinessService businessService;
	@Autowired
	private RollScreenService rollScreenService;
	@Autowired
	private HangStoreService hangStoreService;
	@Autowired
	private ConcessionService concessionService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ActivityTimeService activityTimeService;
	@Autowired
	private ActivityProductService activityProductService;
	@Autowired
	private ShoppingCartService shoppingCartService;
	@Autowired
	private ShopService shopService;
	
	/**
	 * 用户进入商户主页，显示商户下的商品列表
	 * @param sid
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = {"index", ""})
	public String showBusinessIndex(
			String sid,
			String mobile,
			@RequestParam(value="username", required=false, defaultValue="")String username,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("appId", appId);
		//挂滚动屏
		RollScreen rollScreen = new RollScreen();
		rollScreen.setMerchant(merchant);
        model.addAttribute("rollScreenPage", rollScreenService.find(new Page<RollScreen>(request, response), rollScreen));
        //挂电商
        HangStore hangStore = new HangStore();
        hangStore.setMerchant(merchant);
        model.addAttribute("hangStorePage", hangStoreService.find(new Page<HangStore>(request, response), hangStore));
		//最新优惠
        Concession concession = new Concession();
        concession.setMerchant(merchant);
        Page<Concession> page = concessionService.find(new Page<Concession>(request, response), concession); 
        if (page.getList().size() > 0) {
        	model.addAttribute("concession", page.getList().get(0));
		}
        //抢购活动信息
        Activity activity = new Activity();
        activity.setMerchant(merchant);
        activity.setType("1");
        Page<Activity> activityPage = activityService.find(new Page<Activity>(request, response), activity); 
        if (activityPage.getList().size() > 0) {
        	activity = activityPage.getList().get(0);
        	String nowDate = DateUtils.getDate();
        	Date now = new Date();
        	int timeNum=0;
        	for (ActivityTime time : activity.getTimeList()) {
        		//判断是否为今天日期
        		if (DateUtils.formatDate(time.getActivityDate(), DateUtils.parsePatterns[0]).equals(nowDate)) {
        			Date endDate = DateUtils.parseDate(nowDate+" "+time.getEndTime(), DateUtils.parsePatterns[2]);
        			if (now.getTime()<endDate.getTime()) {
        				activity.setActivityDate(time.getActivityDate());
        				activity.setStartTime(time.getStartTime());
        				activity.setEndTime(time.getEndTime());
        				break;
        			}
				}else if (time.getActivityDate().getTime()>DateUtils.parseDate(nowDate, DateUtils.parsePatterns[0]).getTime()) {
					activity.setActivityDate(time.getActivityDate());
    				activity.setStartTime(time.getStartTime());
    				activity.setEndTime(time.getEndTime());
    				break;
				}
        		timeNum++;
    			if (timeNum==activity.getTimeList().size()) {
    				timeNum=(activity.getTimeList().size()-1);
    			}
			}
        	model.addAttribute("timeNum", timeNum);
        	model.addAttribute("activity", activity);
		}
        return "mobile/business/index";
	}
	
	/**
	 * 跳转到最新优惠页面
	 * @param concession
	 * @param sid
	 * @param mobile
	 * @param username
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "concession")
	public String showConcession(
			Concession concession,
			String sid,
			String mobile,
			@RequestParam(value="username", required=false, defaultValue="")String username,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		Merchant merchant = ShopUtils.getMerchantById(sid);
		concession = concessionService.get(concession.getId());
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("appId", appId);
		model.addAttribute("concession", concession);
		return "mobile/business/concession";
	}
	
	/**
	 * 乐活抢购
	 * @param activity
	 * @param sid
	 * @param mobile
	 * @param username
	 * @param appId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "activity")
	public String showActivity(
			Activity activity,
			String sid,
			String mobile,
			@RequestParam(value="username", required=false, defaultValue="")String username,
			@RequestParam(value="appId", required=false, defaultValue="")String appId,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		User user = UserUtils.getShopUser(mobile);
		if(user==null) user = new User();
		Merchant merchant = ShopUtils.getMerchantById(sid);
		activity = activityService.get(activity.getId());
    	String nowDate = DateUtils.getDate();
    	Date now = new Date();
    	int timeNum=0;
    	for (ActivityTime time : activity.getTimeList()) {
    		//判断是否为今天日期
    		if (DateUtils.formatDate(time.getActivityDate(), DateUtils.parsePatterns[0]).equals(nowDate)) {
				Date endDate = DateUtils.parseDate(nowDate+" "+time.getEndTime(), DateUtils.parsePatterns[2]);
				if (now.getTime()<endDate.getTime()) {
					activity.setActivityDate(time.getActivityDate());
					activity.setStartTime(time.getStartTime());
					activity.setEndTime(time.getEndTime());
					break;
				}
    		}else if (time.getActivityDate().getTime()>DateUtils.parseDate(nowDate, DateUtils.parsePatterns[0]).getTime()) {
				activity.setActivityDate(time.getActivityDate());
				activity.setStartTime(time.getStartTime());
				activity.setEndTime(time.getEndTime());
				break;
			}
			timeNum++;
			if (timeNum==activity.getTimeList().size()) {
				timeNum=(activity.getTimeList().size()-1);
			}
		}
    	ActivityTime activityTime = new ActivityTime();
    	if (activity.getTimeList().size()>0) {
    		activityTime = activity.getTimeList().get(timeNum);
		}
		for (ActivityProduct actProduct : activityTime.getProductList()) {
			String actProductId = actProduct.getId();
			List<ShoppingCart> cartList = activityProductService.getCartList(actProductId, user.getId());
			if(cartList==null) cartList = Lists.newArrayList();
			actProduct.setCartList(cartList);
			if (actProduct.getCartList().size()>0) {
				actProduct.setCartId(actProduct.getCartList().get(0).getId());
				actProduct.setBuyState(1);
			}
		}
    	
    	//获取购物车数量信息
		List<ShoppingCart> carts = Lists.newArrayList();
		if(UserUtils.getShopUser(mobile) != null){
			carts = shopService.findShoppingCarts(sid, UserUtils.getShopUser(mobile).getId());
		}
		//定义保存购买总数量和总金额变量
		int totalNumber=0;
		double totalAmount=0.00;
		for (ShoppingCart cart : carts) {
			totalNumber += cart.getNumber();
			totalAmount += cart.getAmount();
		}
		model.addAttribute("totalNumber", totalNumber);
		model.addAttribute("totalAmount", FloatFormat.m1(totalAmount));
		//
    	model.addAttribute("timeNum", timeNum);
    	model.addAttribute("activity", activity);
		model.addAttribute("activityTime", activityTime);
		model.addAttribute("merchant", merchant);
		model.addAttribute("mobile", mobile);
		model.addAttribute("appId", appId);
		return "mobile/business/activity";
	}
	
	@RequestMapping(value = "activity/getActivityTime")
	public @ResponseBody Object getActivityTime(
			String timeId,
			String mobile,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		User user = UserUtils.getShopUser(mobile);
		if(user == null){
			user = new User();
		}
    	ActivityTime activityTime = activityTimeService.get(timeId);
    	if(activityTime.getProductList().size()>0){
			for (ActivityProduct actProduct : activityTime.getProductList()) {
				String actProductId = actProduct.getId();
				List<ShoppingCart> cartList = activityProductService.getCartList(actProductId, user.getId());
				if(cartList==null) cartList = Lists.newArrayList();
				actProduct.setCartList(cartList);
				if (actProduct.getCartList().size()>0) {
					actProduct.setCartId(actProduct.getCartList().get(0).getId());
					actProduct.setBuyState(1);
				}
			}
    	}
    	//封装json数据
    	JSONObject rtnData = new JSONObject();
    	rtnData.put("status", 200);
    	rtnData.put("message", "成功");
    	rtnData.put("id", activityTime.getId());
    	rtnData.put("activityDate", activityTime.getActivityDateStr());
    	rtnData.put("startTime", activityTime.getStartTime());
    	rtnData.put("endTime", activityTime.getEndTime());
    	JSONArray productList = new JSONArray();
		if (activityTime.getProductList()!=null && activityTime.getProductList().size() > 0) {
			for (ActivityProduct bean : activityTime.getProductList()) {
				JSONObject activityProduct = new JSONObject();
				activityProduct.put("id", bean.getId());
				activityProduct.put("number", bean.getNumber());
				activityProduct.put("buyNumber", bean.getBuyNumber());
				activityProduct.put("price", bean.getPrice());
				activityProduct.put("buyState", bean.getBuyState());
				activityProduct.put("cartId", bean.getCartId());
				JSONObject product = new JSONObject();
				product.put("id", bean.getProduct().getId());
				product.put("name", bean.getProduct().getName());
				product.put("price", bean.getProduct().getPrice());
				product.put("logoUrl", bean.getProduct().getLogoUrl());
				activityProduct.put("product", product);
				productList.add(activityProduct);
			}
		}
		rtnData.put("productList", productList);
		return rtnData;
	}
	
	/**
	 * 进行抢购
	 * @param sid
	 * @param mobile
	 * @param productId
	 * @param actProductId
	 * @param price
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "activity/panicBuy")
	public @ResponseBody 
		Object doPanicBuy(
			String sid,
			String mobile,
			String productId,
			String actProductId,
			String cartId,
			double price,
			HttpServletRequest request, HttpServletResponse response, Model model){
		//处理mobile参数
		if(StringUtils.isNotBlank(mobile))mobile = mobile.split(",")[0];
		ActivityProduct ap = activityProductService.get(actProductId);
		if (ap==null || StringUtils.isBlank(ap.getId())) {
			return getStatusBean(404, "抢购商品不存在，请刷新后重试.");
		}else {
			if (ap.getBuyNumber()>=ap.getNumber()) { //已抢光了
				return getStatusBean(400, "抱歉！动作太慢了，已经抢光了！");
			}else {
				ap.setBuyNumber(ap.getBuyNumber()+1);
				activityProductService.save(ap); //已抢购数量+1
				//添加抢购到购物车
				ShoppingCart cart = shoppingCartService.get(cartId);
				User user = UserUtils.getShopUser(mobile);
				if (cart==null || StringUtils.isBlank(cartId)) {
					cart = new ShoppingCart();
					cart.setId(IdGen.uuid());
					cart.setMerchant(new Merchant(sid));
					cart.setUser(user);
					cart.setCreateBy(user);
					cart.setUpdateBy(user);
					cart.setProduct(new Product(productId));
					cart.setNumber(1);
					cart.setPrice(price);
					cart.setAmount(1*price);
					List<ActivityProduct> actProductList = Lists.newArrayList();
					actProductList.add(activityProductService.get(actProductId));
					cart.setActProductList(actProductList);
					cart.prePersist();
				}else {
					cart.setNumber(cart.getNumber()+1);
					cart.setPrice(price);
					cart.setAmount(FloatFormat.m2(cart.getNumber()*cart.getPrice()));
				}
				shoppingCartService.save(cart);
				return getStatusBean(200, cart.getId()+"_"+ap.getBuyNumber()+"_恭喜，抢购成功！请在30分钟内完成您的订单.");
			}
		}
	}
}
